package com.huike.service.login.impl;

import cn.hutool.core.date.DateException;
import com.github.pagehelper.util.StringUtil;
import com.huike.utils.JwtClaimsConstant;
import com.huike.utils.JwtUtil;
import com.huike.vo.LoginVO;
import com.huike.mapper.user.UserMapper;
import com.huike.service.login.LoginService;
import com.huike.pojo.User;
import com.huike.properties.JwtProperties;
import com.huike.utils.VerifyCode;
import com.huike.dto.LoginDTO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import com.huike.result.Result;
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;

    //验证码图片生成
    public Map<String,Object> getVerificationCode() {


            int width = 200;
            int height = 69;
            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            //生成对应宽高的初始图片
            String randomText = VerifyCode.drawRandomText(width, height, verifyImg);

            //单独的一个类方法，出于代码复用考虑，进行了封装。
            //功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符
        redisTemplate.opsForValue().set("code",randomText);
        String code = (String) redisTemplate.opsForValue().get("code");
        System.out.println(code);
            System.out.println(randomText);
        String img = BufferedImageToBase64(verifyImg);
        Map<String, Object> map = new HashMap<>();
        map.put("img",img);
        return map;
    }

    //登录功能
    @Override
    public Result<LoginVO> login(LoginDTO vo) throws UnsupportedEncodingException {
        //无用判断,前端已经写死了,少写一个都发不过来
        if (null==vo|| StringUtil.isEmpty(vo.getCode())){
            throw new DateException("数据异常");
        }
        String password = vo.getPassword();
        //判断长度
        if (vo.getUsername().length()>11||password.length()<6||password.length()>12){
            throw new DateException("数据异常");
        }
        //根据用户名查询用户信息
        User user= userMapper.selectUserByUsername(vo.getUsername());
        System.out.println(user);
        if (null==user){
            throw new DateException("用户不存在");
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));
        System.out.println(password);
        if (!user.getPassword().equals(password)){
            throw new DateException("用户或密码不正确");
        }
        String code =(String) redisTemplate.opsForValue().get("code");
        if (null==code||!code.equals(vo.getCode())){
            throw new DateException("验证码错误");
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.EMP_ID, user.getUserId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                map);
        LoginVO loginVO = LoginVO.builder()
                .userName(user.getUserName())
                .id(user.getUserId())
                .name(user.getNickName())
                .token(token)
                .build();
        return Result.success(loginVO);
    }
    //转换BufferedImage为Base64
    private static String BufferedImageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return png_base64;
    }


}
